import React, { Component } from 'react';
import Divider from 'material-ui/Divider';
import TextField from 'material-ui/TextField';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import { grey500 } from 'material-ui/styles/colors';
import { Card, CardMedia, CardTitle } from 'material-ui/Card';
import FloatingActionButton from 'material-ui/FloatingActionButton';

import io from 'socket.io-client';

import CONFIG from '../../config';
import CommentList from './CommentList';
import { moment } from '../Utils/Helper';
import { parseJSON, getMethod, postJsonMethod } from '../../redux/Helper';

export default class ShowCommentPanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      comments: [],
      nextPageUrl: null,
      isFetching: false,
      comment: '',
    }
  }
  
  componentWillMount() {
    this.initFetch();
  }

  /**
   * 与活动相关才可以加入房间
   */
  componentDidMount() {
    if (this.props.isParticipant || this.props.isPublisher) {
      // 群聊socket
      this.comment = io.connect('/comment');

      // 加入房间
      let commentId = `comment-${this.props.data.id}`;
      this.comment.emit('joinComments', commentId);

      // 获取评论立即渲染至视图
      this.comment.on('get comment', (msg) => {
        const arr = [...this.state.comments, msg];
        this.setState({comments: arr})
      });
    }
  }

  componentWillUpdate() {
    this.formerComLength = this.state.comments.length;
    this.formerScrollHeight = this.refs.commentContent.scrollHeight;
  }

  componentDidUpdate() {
    let comLength = this.state.comments.length;
    if (comLength - this.formerComLength === 1) {
      this.refs.commentContent.scrollTop = this.refs.commentContent.scrollHeight;
    } else if (comLength - this.formerComLength > 1) {
      if (this.formerScrollHeight === 420) {
        this.refs.commentContent.scrollTop = this.refs.commentContent.scrollHeight;
      } else {
        this.refs.commentContent.scrollTop = this.refs.commentContent.scrollHeight - this.formerScrollHeight;
      }
    }
  }

  /**
   * 获取初始数据
   */
  initFetch = () => {
    let request = `?token=${this.props.token}`;
    let url = `${CONFIG.apiHost}/api/activity/show/${this.props.data.id}/comment${request}`;

    this.setState({isFetching: true});
    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      if (res.msg.next_page_url) {
        this.setState({isFetching: true});
      }else{
        this.setState({isFetching: false});
      }
      this.setState({
        nextPageUrl: res.msg.next_page_url,
        comments: res.msg.data.reverse()
      });
    })
  };

  /**
   * 加载评论信息
   */
  fetchComment = () => {
    if (this.state.nextPageUrl) {
      let arr = this.state.comments;
      let request = `&token=${this.props.token}`;
      let url = `${this.state.nextPageUrl}${request}`;
 
      this.setState({isFetching: true});
      fetch(url, getMethod)
      .then(parseJSON)
      .then(res => {
        this.setState({
          isFetching: false,
          nextPageUrl: res.msg.next_page_url,
          comments: res.msg.data.reverse().concat(arr)
        });
      });
    }else{
      this.setState({isFetching: false});
    }
  };

  /**
   * 保存评论state
   */
  handleComment = (e, v) => {
    this.setState({comment: v});
  };

  /**
   * 绑定键盘的enter键
   */
  handleOnKeyDown = (event) => {
    if (event.keyCode === 13) {
      this.refs.submitTextarea.blur()
      this.submit();
    }
  };

  /**
   * 提交评论
   */
  submit = () => {
    if (this.state.comment) {
      let data = {
        user_id: this.props.userId,
        user_img: this.props.userImg,
        user_name: this.props.userName,
        comment: this.state.comment,
        created_at: moment().format()
      };
      let request = `?token=${this.props.token}`;
      let url = `${CONFIG.apiHost}/api/activity/comment/${this.props.data.id}${request}`;
      let commentId = `comment-${this.props.data.id}`;

      fetch(url, postJsonMethod(data))
      .then(this.setState({comment: ''}))
      .then(this.comment.emit('comment', commentId, data))
    }
  };

  /**
   * 活动是否过期
   * @param startTime
   * @return true|false
   */
  _compareStartTime = (startTime) => {
    if (!startTime) {
      return false;
    }

    if (new Date() > new Date(startTime)) {
      return true;
    }

    return false;
  };

  /**
   * 申请加入活动
   */
  // is_apply_activity,is_join_activity
  add = () => {
    this.props.changeInActivity(1);

    let url = `${CONFIG.apiHost}/api/activity/apply/${this.props.data.id}?token=${this.props.token}`;

    let data = {user_id: this.props.userId};

    fetch(url, postJsonMethod(data));
  };

  /**
   * 取消申请
   */
  cancel = () => {
    this.props.changeInActivity(0);

    let url = `${CONFIG.apiHost}/api/activity/apply/cancel/${this.props.data.id}?token=${this.props.token}`;

    let data = {user_id: this.props.userId};

    fetch(url, postJsonMethod(data));
  };

  render() {
    const { data, color500 } = this.props;

    let cover = (
      <CardMedia 
        overlay={this._compareStartTime(data.start_time) ? 
          <CardTitle subtitle="活动已过期" /> : <div></div>
        }
        overlayContentStyle={{padding: 0}}
      >
        <img src={data.cover} />
      </CardMedia>
    );

    let contents = (
      <div>
        <FlatButton 
          style={styles.more}
          onClick={this.fetchComment}
          disabled={this.state.nextPageUrl ? false : true}
          label={this.state.nextPageUrl ? '查看更多' : '没有更多了'}
        />
        
        <div style={styles.commentBox}>
          {this.state.comments.map((item, index) => {
            let createdAt;
            
            if (!this.nextTimestamp) {
              this.nextTimestamp = moment(item.created_at).unix() - 600;
            }

            let thisTimestamp = moment(item.created_at).unix();
            let secondRange = thisTimestamp - this.nextTimestamp;

            if (index === 0) {
              secondRange = 600;
            }

            if (secondRange >= 600) {
              let a = moment(moment().format('YYYY-MM-DD'));
              let b = moment(moment(item.created_at).format('YYYY-MM-DD'));
              let dayRange = a.diff(b, 'days');
              if (dayRange === 0) {
                createdAt = moment(item.created_at).format('LT')
              } else if (dayRange === 1) {
                createdAt = moment(item.created_at).subtract(0, 'days').calendar()
              } else if (dayRange > 1 && dayRange <= 7) {
                createdAt = moment(item.created_at).format('dddd h:mm')
              } else {
                createdAt = moment(item.created_at).format('lll')
              }
              this.nextTimestamp = moment(item.created_at).unix();
            }

            return (
              <CommentList 
                key={index} 
                item={item}
                userId={this.props.userId}
                createdAt={createdAt}
              />
            );
          })}
        </div>
      </div>
    );

    let submitField = (
      <div style={styles.sendBox}>
        <div style={styles.float}>
          <TextField
            ref='submitTextarea'
            fullWidth={true}
            underlineShow={false}
            multiLine={true}
            hintText="开始写下信息 ..."
            value={this.state.comment}
            onChange={this.handleComment.bind(this)}
            onKeyDown={this.handleOnKeyDown.bind(this)}
            hintStyle={styles.text}
            textareaStyle={styles.text}
          />
          <FloatingActionButton 
            zDepth={0}
            mini={true}
            style={styles.btn}
            iconClassName='icon-send'
            backgroundColor='#fff'
            iconStyle={{color: this.props.color500}}
            onTouchTap={this.submit.bind(this)}
          />
        </div>
      </div>
    );

  	return (
      <Card style={{position: 'relative'}}>
        <div style={styles.title}>{data.title}
          {this.props.isParticipant || this.props.isPublisher ? 
            <IconButton
              touch={true}
              iconClassName='icon-mode_edit'
              tooltipPosition='bottom-left'
              tooltip='活动发生了什么有趣事？'
              iconStyle={{color: grey500}}
              onTouchTap={this.props.handleOpen.bind(this, 'openTweet')}
            />
            : <IconButton
              touch={true}
              iconClassName='icon-exposure_plus_1'
              tooltipPosition='bottom-left'
              tooltip={data.is_apply_activity == 0 ? '申请加入' : '取消加入'}
              iconStyle={{color: data.is_apply_activity === 0 ? grey500 : color500}}
              onTouchTap={data.is_apply_activity == 0 ? this.add : this.cancel}
            />
          }
        </div>
        <Divider />
        {this.props.isParticipant || this.props.isPublisher ? 
          <div>
            <div ref='commentContent' style={{height: 500, overflowY: 'auto'}}>
              {cover}
              {contents}
            </div>
            
            {submitField}
          </div>
          : <div ref='commentContent'>{cover}</div>
        }
      </Card>
  	);
  }
};

const styles = {
  title: {
    paddingLeft: 16,
    paddingTop: 8,
    paddingBottom: 8,
    paddingRight: 8,
    fontSize: 20,
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  commentBox: {
    paddingTop: 0,
    paddingBottom: 0,
    paddingLeft: 16,
    paddingRight: 16
  },
  sendBox: {
    padding: 0,
    borderTopStyle: 'solid',
    borderTopColor: 'rgb(224, 224, 224)',
    borderTopWidth: 1,
  },
  float: {
    position: 'relative',
    paddingTop: 0,
    paddingBottom: 0,
    paddingLeft: 0,
    paddingRight: 88,
  },
  text: {
    paddingTop: 12,
    paddingBottom: 12,
    paddingLeft: 16,
    paddingRight: 16,
  },
  btn: {
    position: 'absolute',
    top: 16,
    right: 16
  },
  more: {
    width: '100%',
    borderRadius: 0
  }
};